package il.technion.ewolf.beehive.handlers;

import il.technion.ewolf.beehive.cache.Storage;
import il.technion.ewolf.kbr.Key;
import il.technion.ewolf.kbr.KeyFactory;
import il.technion.ewolf.kbr.openkad.handlers.AbstractHandler;
import il.technion.ewolf.kbr.openkad.msg.KadMessage;
import il.technion.ewolf.kbr.openkad.msg.StoreRequest;
import il.technion.ewolf.kbr.openkad.net.MessageDispatcher;
import il.technion.ewolf.kbr.openkad.net.filter.MessageFilter;
import il.technion.ewolf.kbr.openkad.net.filter.TypeMessageFilter;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;

import com.google.inject.Inject;
import com.google.inject.Provider;

/**
 * Handle 'ContentMessage' requests by saving the value sent in the storage
 * @author Ligal ligal2@gmail.com
 * @author Hen senderhen@gmail.com
 */
public class BeeHiveContentMessageHandler extends AbstractHandler implements ContentMessageHandler {
	private final Storage localStorage;
	private final KeyFactory keyFactory;
	
	@Inject
	BeeHiveContentMessageHandler(
			Provider<MessageDispatcher<Void>> msgDispatcherProvider,
			KeyFactory factory,
			Storage storage) {
		
		super(msgDispatcherProvider);
		this.localStorage = storage;
		this.keyFactory = factory;
	}

	@Override
	public void completed(KadMessage msg, Void attachment) {
		
		StoreRequest storeMsg = ((StoreRequest)msg);
		
		String tag = storeMsg.getTag();
		if (tag != null && tag.compareTo("SAVE") == 0){
			Serializable value = null;
			//get the value from the message
			value = storeMsg.getContent();
						
			if (value != null) {
				Key key = keyFactory.create(value.toString());
				localStorage.addToLocalStorage(key, value);
				//System.out.println(value.toString() + " saved");
			}
		}
	}

	@Override
	public void failed(Throwable exc, Void attachment) {
		// should never b here
	}

	@Override
	protected Collection<MessageFilter> getFilters() {
		// only accept FindNodeRequests messages
		return Arrays.asList(new MessageFilter[] {
				new TypeMessageFilter(StoreRequest.class)
		});
	}
}
